<?php

namespace app\api\command;

use app\admin\model\share\ShareUser;
use app\common\model\PrepaidLogs;
use app\common\model\ShareConfig;
use think\console\Input;
use think\console\Output;
use think\console\Command;
use addons\shopro\model\Order;
use function fast\e;

class PrepaidClear extends Command
{
    protected function configure()
    {
        $this->setName('prepaid-clear')->setDescription('取消通过易付卷更新得身份');
    }

    protected function execute(Input $input, Output $output)
    {
        $output->info('开始处理');
        PrepaidLogs::chunk(100, function ($logs) use ($output) {
            foreach ($logs as $log) {
                $output->info(sprintf('开始处理用户 %s', $log->user_id));
                $goodsIds = Order::where('user_id', $log->user_id)
                    ->whereIn('status', [
                        1, 2
                    ])
                    ->where('pay_type', '<>', 'prepaid')
                    ->where('platform', '<>', 'prepaid')
                    ->column('goods_id');
                if (count($goodsIds) > 0) {
                    $output->info('用户有除易付卷之外得订单');
                    // 查询该商品里是否带身份
                    $shareConfig = ShareConfig::whereIn('goods_id', $goodsIds)->select();
                    if (count($shareConfig) > 0) {
                        // 如果订单中包含身份商品，则跳过该用户
                        $output->info(sprintf('用户 %s 跳过', $log->user_id));
                        continue;
                    }
                }
                $shareUser = ShareUser::get(['user_id' => $log->user_id]);
                if (!empty($shareUser) && $shareUser->role == 1) {
                    $output->info(sprintf('取消用户 %s 的身份', $log->user_id));
                    $shareUser->role = 0;
                    $shareUser->save();
                }
                $output->info(sprintf('用户 %s 处理完成', $log->user_id));
            }
        });

        echo "ok".date('Y-m-m H:i:s') . PHP_EOL;
    }
}